package ch.zbw.sysventory.server.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ch.zbw.sysventory.server.model.User;
import ch.zbw.sysventory.server.scanner.ScanManager;
import ch.zbw.sysventory.server.service.security.UserService;

@Component
@Controller
public class ScanController {

	@Autowired
	private ScanManager scanManager;

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/scans", method = RequestMethod.GET)
	public ModelAndView showScansSite(Model model) {
		return new ModelAndView("scans");
	}

	@RequestMapping(value = "/startscan", method = RequestMethod.GET)
	public String startScan(Model model) {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (!(auth instanceof AnonymousAuthenticationToken)) {
			User user = this.userService.getByLoginName(auth.getName());
			this.scanManager.startScan(user);
		}
		return "redirect:/scans";
	}

	@RequestMapping(value = "/isScanRunning", method = RequestMethod.GET)
	public ModelAndView checkIfScanIsRunning(Model model) {
		model.addAttribute("isScanRunning", "" + this.scanManager.isJobRunning());
		return new ModelAndView("IsScanRunning");
	}

	@RequestMapping(value = "/getScanLogMessages", method = RequestMethod.GET)
	public ModelAndView getScanLogMessages(Model model) {
		model.addAttribute("messages", this.scanManager.getLogMessages());
		return new ModelAndView("ScanLogMessages");
	}

}
